# -*- coding: utf-8 -*-

import urllib,urllib2,re,xbmcplugin,xbmcgui,os,time

##General vars
__plugin__ = "Hot"
__author__ = "Shmulik"
__credits__ = ""
__USERAGENT__ = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
__XBMC_Revision__ = ""


def getMatches(url,pattern,clear=False):
  data = getData(url)
  if (clear):
    data = data.replace("\n","").replace("\t","").replace("\r","")
  
  matches=re.compile(pattern,re.MULTILINE|re.DOTALL).findall(data)
  return matches

def getData(url):
  cachePath = xbmc.translatePath( os.path.join( os.getcwd(), 'cache','pages',urllib.quote(url,"") ))
  if (os.path.exists(cachePath) and (time.time()-os.path.getmtime(cachePath))/60/60 <= 1):
    f = open(cachePath, 'r')
    ret = f.read()
    f.close()
    return ret
  req = urllib2.Request(url)
  req.add_header('User-Agent', __USERAGENT__)
  response = urllib2.urlopen(req)
  data=response.read()
  response.close()
  f = open(cachePath, 'w')
  f.write(data)
  f.close()
  return data

def getGenereList():
  matches = getMatches("http://hot.ynet.co.il/home/0,7340,L-7250,00.html","style='margin-bottom: 10px; height: 16px; overflow-y: hidden; padding-right: 10px; padding-left: 5px; direction: rtl; text-align: right; font-weight: bold; color: #A10508;'>(.*?)</div>")
  for name in matches:
    u=sys.argv[0]+"?url="+urllib.quote_plus(name)+"&mode=0"
    li=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage="DefaultFolder.png")
    li.setInfo( type="Video", infoLabels={ "Title": urllib.unquote(name) } )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=li,isFolder=True)

def getSeriesList(genere):
  searchArea = getMatches("http://hot.ynet.co.il/home/0,7340,L-7250,00.html",genere+"</div><div class='loc_HOT_FOOTER_column_div(.*?)<div id='links")
  if (len(searchArea) == 0):
    searchArea = getMatches("http://hot.ynet.co.il/home/0,7340,L-7250,00.html",genere+"</div><div class='loc_HOT_FOOTER_column_div(.*?)'width: 970px; height: 8px; overflow: hidden; clear: both;'")
    
  matches = re.compile("<div style='margin-bottom: 5px; text-align: right;'><a href='(/home/.*?)'  >(.*?)</a></div>",re.MULTILINE|re.DOTALL).findall(searchArea[0])
  for url,name in matches:
    u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode=9"
    li=xbmcgui.ListItem(name.replace("&#39;","'"), iconImage="DefaultFolder.png", thumbnailImage="DefaultFolder.png")
    li.setInfo( type="Video", infoLabels={ "Title": urllib.unquote(name) } )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=li,isFolder=True)
  xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')

def getSeasons(url):
  serId = re.compile("/home/0,\d+,L-(\d+),00.html").findall(url)[0] #with # and ^ for speed
  
  seasons = getMatches("http://hot.ynet.co.il"+url,'<tr id=\'tr_\d\'(.*?)</tr>')
  for season in seasons:
    menuItems = re.compile('topSrsLoadVidItems\((.+?)\);">.*?110px;\'>(.+?)<').findall(season)
    if len(menuItems) > 0:
        name = menuItems[0][1]
        t='a'
    else :
        menuItems = re.compile('window.location=\'(.+?)\'">.*?class.*?>(.+?)<').findall(season)
        if len(menuItems) > 0:
            #catId = str(525)# getMatches("http://hot.ynet.co.il"+url," id='firstTypeId' value='(\d+)'")[0]
            url = menuItems[0][0]
            serId = re.compile("/home/0,\d+,L-(\d+),00.html").findall(url)[0] #with # and ^ for speed
            name = menuItems[0][1]
            t='b'
            
    url = "http://hot.ynet.co.il/Ext/Comp/Hot/TopSeriesPlayer_Hot/CdaTopSeriesPlayer_VidItems_Hot/0,13031,L-"+serId+"-"+menuItems[0][0]+"-0-0,00.html"
    
    u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode=1"
    li=xbmcgui.ListItem(name.replace("&#39;","'"), iconImage="DefaultFolder.png", thumbnailImage="DefaultFolder.png")
    li.setInfo( type="Video", infoLabels={ "Title": urllib.unquote(name) } )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=li,isFolder=True)

  
  #getEpisodeList(url)

def getEpisodeList(url):
  
  matches = getMatches(url,"(http:.*?.jpg).*?,(\d+?)\);\"><b>(.*?)</b>")
  for pic,id,name in matches:
    u=sys.argv[0]+"?url="+id+"&mode=2&name="+urllib.quote_plus(name)
    liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=pic)
    liz.setInfo( type="Video", infoLabels={ "Title": urllib.unquote(name) } )
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
  xbmcplugin.setContent(int(sys.argv[1]), 'episodes')

def getFlv(url):
  url = "http://hot.ynet.co.il/Cmn/App/Video/CmmAppVideoApi_AjaxItems/0,0,"+url+"-0,00.html"
  match = getMatches(url,'"path":"(.*?)"')[0]
  xbmc.Player().play(match)
  
  
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param

		
params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

if mode==None or url==None or len(url)<1:
	getGenereList()
elif mode==0:
	getSeriesList(url)
elif mode==9:
	getSeasons(url)
elif mode==1:
	getEpisodeList(url)
elif mode==2:
	getFlv(url)



xbmcplugin.endOfDirectory(int(sys.argv[1]))